package main

import (
	"log"
	"time"

	"gitee.com/z1gotool/gorm2mongo"
	"gitee.com/z1gotool/gorm2mongo/mongoplu"
	"gitee.com/z1gotool/gorm2mongo/z1mongo"
	"gitee.com/z1gotool/gormplugin/z1util"
	"gitee.com/z1gotool/z1err"
	"go.mongodb.org/mongo-driver/bson/primitive"
	"go.mongodb.org/mongo-driver/mongo"
	"gorm.io/gorm"
	"gorm.io/plugin/soft_delete"
)

func main() {
	// https://github.com/go-gorm/gorm/issues/3565
	// https://juejin.cn/post/7131258433948352520

	var db *gorm.DB
	var mdb *mongo.Database
	{
		dbTmp, mdbTmp, err := gorm2mongo.NewDB(gorm2mongo.MongoInfo{
			Uri:          `mongodb://localhost:27017`,
			DBName:       `z1mongo`,
			Timeout:      15,
			ClientMaxNum: 100,
		}, gorm.Config{})
		z1err.Check(err)

		db = dbTmp
		mdb = mdbTmp
	}

	// db.AutoMigrate(&User{})

	if false {
		// create
		if true {
			user := []User{
				{
					ID:   123456789012345678,
					Name: `张三1`,
				},
				{
					ID:   time.Now().Unix(),
					Name: `张三`,
				},
			}

			txSql := db.Session(&gorm.Session{DryRun: true})
			txSql = txSql.Model(&User{})
			txSql = txSql.Create(&user)

			sql := db.Dialector.Explain(
				txSql.Statement.SQL.String(),
				txSql.Statement.Vars...,
			)

			log.Println(z1mongo.Sql2Mongo(db, mdb, sql, false, true))
		}

		// update
		if true {
			txSql := db.Session(&gorm.Session{DryRun: true})
			txSql = txSql.Model(&User{})
			txSql = txSql.Where(&User{Name: `张三1`})
			txSql = txSql.Updates(&User{
				Name: `zhangsan`,
			})

			sql := db.Dialector.Explain(
				txSql.Statement.SQL.String(),
				txSql.Statement.Vars...,
			)

			log.Println(sql)
			log.Println(z1mongo.Sql2Mongo(db, mdb, sql, false, true))
		}

		// find
		if true {

			user := User{}
			txSql := db.Session(&gorm.Session{DryRun: true})
			txSql = txSql.Where(&User{
				Name: `张三`,
			})
			txSql = txSql.Find(&user)

			sql := db.Dialector.Explain(
				txSql.Statement.SQL.String(),
				txSql.Statement.Vars...,
			)

			log.Println(z1mongo.Sql2Mongo(db, mdb, sql, false, true))
		}

		// delete
		if true {
			txSql := db.Session(&gorm.Session{DryRun: true})
			txSql = txSql.Model(&User{})
			txSql = txSql.Where(&User{Name: `张三`})
			txSql = txSql.Unscoped() // Delete permanently
			txSql = txSql.Delete(&User{})

			sql := db.Dialector.Explain(
				txSql.Statement.SQL.String(),
				txSql.Statement.Vars...,
			)

			log.Println(z1mongo.Sql2Mongo(db, mdb, sql, false, true))
		}
	}

	if true {
		Z1DB := db

		Z1DB.Use(&mongoplu.ToMongo{})

		Z1DB = z1util.UpdateDBContext(`z1mongoShowQuery`, false, Z1DB, false)

		// global set DryRun = true
		Z1DB.DryRun = true

		db = Z1DB

		// create
		if true {
			user := []User{
				{
					ID:   123456789012345678,
					Name: `张三1`,
				},
				{
					ID:   time.Now().Unix(),
					Name: `张三`,
				},
			}

			txSql := db.Session(&gorm.Session{DryRun: true})
			txSql = z1util.UpdateDBContext(`z1mongoShowQuery`, true, txSql, false)
			txSql = txSql.Model(&User{})
			txSql = txSql.Create(&user)

			log.Println(txSql.RowsAffected)
		}

		// update
		if true {
			txSql := db.Session(&gorm.Session{DryRun: true})
			txSql = txSql.Model(&User{})
			txSql = txSql.Where(&User{Name: `张三1`})
			txSql = txSql.Updates(&User{
				Name: `zhangsan`,
			})

			log.Println(txSql.RowsAffected)
		}

		// find
		if true {

			user := []User{}
			txSql := db.Session(&gorm.Session{DryRun: true})
			txSql = txSql.Where(&User{
				Name: `张三`,
			})
			txSql = txSql.Find(&user)

			log.Println(txSql.RowsAffected, user)
		}

		// delete
		if true {
			txSql := db.Session(&gorm.Session{DryRun: true})
			txSql = txSql.Model(&User{})
			txSql = txSql.Where(&User{Name: `张三`})
			txSql = txSql.Unscoped() // Delete permanently
			txSql = txSql.Delete(&User{})

			log.Println(txSql.RowsAffected)
		}
	}

}

type User struct {
	// gorm.Z1Model
	ID        int64                 `gorm:"column:id;primarykey" json:"id" bson:"id"`
	CreatedAt int64                 `gorm:"column:created_at;not null" json:"created_at" bson:"created_at"`
	UpdatedAt int64                 `gorm:"column:updated_at;not null" json:"updated_at" bson:"updated_at"`
	DeletedAt soft_delete.DeletedAt `gorm:"column:deleted_at;index;not null;default:0" json:"deleted_at" bson:"deleted_at"`
	ID_       primitive.ObjectID    `gorm:"-:all" json:"_id" bson:"_id"`
	// ----------------
	Username    string `gorm:"column:username;NOT NULL" json:"username" bson:"username"`              // 账号名称
	Password    string `gorm:"column:password;NOT NULL" json:"password" bson:"password"`              // 加密后的密码
	RoleID      int64  `gorm:"column:role_id;default:0;NOT NULL" json:"role_id" bson:"role_id"`       // 角色id
	Name        string `gorm:"column:name;NOT NULL" json:"name" bson:"name"`                          // 用户名
	Status      int64  `gorm:"column:status;default:1;NOT NULL" json:"status" bson:"status"`          // 用户状态：1正常，2禁用
	Type        int64  `gorm:"column:type;default:2;NOT NULL" json:"type" bson:"type"`                // 管理员类型 1-超级管理员 2-普通管理员
	Usbkey      int64  `gorm:"column:usbkey;default:0;NOT NULL" json:"usbkey" bson:"usbkey"`          // usbkey id
	Keyuid      string `gorm:"column:keyuid;NOT NULL" json:"keyuid" bson:"keyuid"`                    // 设备唯一硬件 ID
	Keypwd      string `gorm:"column:keypwd;NOT NULL" json:"keypwd" bson:"keypwd"`                    // 设备密码
	ServerSeed  string `gorm:"column:server_seed;NOT NULL" json:"server_seed" bson:"server_seed"`     // 种子码
	MobilePhone string `gorm:"column:mobile_phone" json:"mobile_phone" bson:"mobile_phone"`           // 手机号码
	Cid         string `gorm:"column:cid" json:"cid" bson:"cid"`                                      // 18位身份证号
	MobileLogin int64  `gorm:"column:mobile_login;default:0" json:"mobile_login" bson:"mobile_login"` // 使用手机验证码登录---1允许2不允许
	ApiToken    string `gorm:"column:api_token;NOT NULL" json:"api_token" bson:"api_token"`           // 接口token
	Extend      string `gorm:"column:extend" json:"extend" bson:"extend"`                             // 扩展字段为json
	PlaceID     int64  `gorm:"column:place_id;default:0;NOT NULL" json:"place_id" bson:"place_id"`    // 场所id
}

type Role struct {
	// gorm.Z1Model
	ID        int64                 `gorm:"column:id;primarykey" json:"id" bson:"id"`
	CreatedAt int64                 `gorm:"column:created_at;not null" json:"created_at" bson:"created_at"`
	UpdatedAt int64                 `gorm:"column:updated_at;not null" json:"updated_at" bson:"updated_at"`
	DeletedAt soft_delete.DeletedAt `gorm:"column:deleted_at;index;not null;default:0" json:"deleted_at" bson:"deleted_at"`
	ID_       primitive.ObjectID    `gorm:"-:all" json:"_id" bson:"_id"`
	// ----------------
	Name        string `gorm:"column:name;NOT NULL" json:"name" bson:"name"`                      // 角色名称
	Description string `gorm:"column:description;NOT NULL" json:"description" bson:"description"` // 角色描述
	Privileges  string `gorm:"column:privileges;NOT NULL" json:"privileges" bson:"privileges"`    // 访问权限（逗号隔开）
	Status      int64  `gorm:"column:status;default:1;NOT NULL" json:"status" bson:"status"`      // 状态：1正常，2禁用
	PlaceID     int64  `gorm:"column:place_id;default:0;NOT NULL" json:"place_id" bson:"place_id"`
}
